<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="form.spuName" style="width: 50%"></el-input>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="form.description"
          style="width: 50%"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="selectTradeMark" placeholder="请选择品牌">
          <el-option
            v-for="obj in tradeMarkList"
            :key="obj.id"
            :label="obj.tmName"
            :value="obj.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          style="float: left"
          class="avatar-uploader"
          action="dev-api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <div class="el-icon-plus avatar-uploader-icon"></div>
        </el-upload>
        <div style="float: left">
          <div
            class="showImgMaskLayer"
            style="
              display: inline-block;
              margin: 0 5px;
              border-radius: 4px;
              border: 1px solid #f4f4f4;
              position: relative;
            "
            v-for="(obj, i) in form.spuImageList"
            :key="i"
          >
            <img :src="obj.imgUrl" class="avatar" />
            <!-- 遮罩层 -->
            <div class="imgMaskLayer">
              <i
                class="el-icon-delete"
                style="position: absolute; top: 43%; left: 43%; font-size: 2em"
                @click.prevent="delSpuImg(obj)"
              ></i>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="售卖属性">
        <el-select v-model="currentAttrId">
          <el-option
            v-for="obj in attrList"
            :key="obj.id"
            :label="obj.name"
            :value="obj.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-cion-puls"
          @click="addAttrInfo"
          :disabled="!currentAttrId"
          >添加</el-button
        >
        <!-- 已添加表格 -->
        <el-table border :data="form.spuSaleAttrList" style="width: 100%">
          <el-table-column
            label="序号"
            width="80"
            align="center"
            type="index"
          ></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值">
            <template slot-scope="{ row }">
              <div
                v-for="(obj, i) in row.spuSaleAttrValueList"
                :key="obj.id"
                style="display: inline-block; margin: 0 10px"
              >
                <el-input
                  :ref="i"
                  v-if="obj.flag"
                  size="mini"
                  v-model="obj.saleAttrValueName"
                  style="min-width: 50%"
                  @blur="obj.flag = false"
                  @keyup.native.enter="obj.flag = false"
                ></el-input>
                <el-tag
                  v-else
                  disable-transitions
                  type="success"
                  closable
                  @close="dealCloseTag(obj, row)"
                  @click="clickTag(obj, i)"
                >
                  {{ obj.saleAttrValueName }}</el-tag
                >
              </div>

              <el-button size="mini" @click="addAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button size="mini" type="danger" @click="delSaleAttr(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 保存取消 -->
      <el-button
        type="primary"
        @click="saveInfo"
        :disabled="!form.spuName.trim()"
      >
        保存</el-button
      >
      <el-button type="" @click="cancel"> 取消</el-button>
    </el-form>
  </div>
</template>

<script>
import changeShow from '../changeShow'
export default {
  props: ['attrList', 'tradeMarkList', 'category3Id'],
  watch: {
    category3Id: {
      immediate: true,
      handler(newVal) {
        this.form.category3Id = newVal
      }
    }
  },
  data() {
    return {
      selectTradeMark: '请选择品牌',
      currentAttrId: '',
      form: {
        // 父组件传递
        category3Id: '',
        description: '',
        // 添加时无spuid
        id: undefined,
        // 品牌ID
        tmId: '',
        spuName: '',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: '',
          //   imgUrl: '',
          //   spuId: undefined
          // }
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: '',
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: '',
          //       saleAttrName: '',
          //       saleAttrValueName: '',
          //       spuId: undefined
          //     }
          //   ]
          // }
        ]
      }
    }
  },
  methods: {

    // 编辑spu
    async getSpuInfoToEdit(spuId) {
      const res = await this.$API.spu.getSpuInfo(spuId)
      if (res.code == 200) {
        // 添加flag
        res.data.spuSaleAttrList.forEach((item) => {
          item.spuSaleAttrValueList.forEach((value) => {
            value['flag'] = false
          })
        })
        // 显示选择的品牌 selectTradeMark
        this.tradeMarkList.forEach((item) => {
          if (item.id == res.data.tmId) {
            this.selectTradeMark = item.tmName
          }
        })
        // 无spuImageList
        if (!res.data.spuImageList) {
          res.data.spuImageList = []
        }
        // 无spuSaleAttrList
        if (!res.data.spuSaleAttrList) {
          res.data.spuSaleAttrList = []
        }
        this.form = res.data
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + res.data || ''
        })
      }

      // 显示该组件
      this.emitchangeShow(false, changeShow.addSpu)
    },
    delSaleAttr(row) {
      this.form.spuSaleAttrList.splice(
        this.form.spuSaleAttrList.indexOf(row),
        1
      )
    },
    // 点击tag,input显示并聚焦
    clickTag(obj, i) {
      obj.flag = true
      this.$nextTick(() => {
        //获取相应的input表单元素实现聚焦
        this.$refs[i][0].focus()
      })
    },
    //删除属性值
    dealCloseTag(obj, row) {
      row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(obj), 1)
    },
    // 添加属性值
    addAttrValue(row) {
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: '',
        spuId: this.form.id,
        flag: true
      })
      let i = row.spuSaleAttrValueList.length - 1
      // input自动聚焦
      this.$nextTick(() => {
        this.$refs[i][0].focus()
      })
    },
    // 添加售卖属性,最多三个
    addAttrInfo() {
      if (!this.form.spuSaleAttrList) {
        this.form.spuSaleAttrList = []
      }
      if (this.form.spuSaleAttrList.length < 3) {
        let obj = null
        // 找到选择的属性
        this.attrList.forEach((item) => {
          if (item.id == this.currentAttrId) {
            obj = {
              baseSaleAttrId: item.id,
              saleAttrName: item.name,
              spuSaleAttrValueList: [],
              spuId: this.form.id
            }
          }
        })

        if (this.form.spuSaleAttrList.length == 0) {
          this.form.spuSaleAttrList.push(obj)
        } else {
          // 判断是否重复添加
          for (let i = 0; i < this.form.spuSaleAttrList.length; i++) {
            if (
              this.form.spuSaleAttrList[i].baseSaleAttrId == obj.baseSaleAttrId
            ) {
              this.$message({ type: 'warning', message: '该属性已经添加' })
              return
            }
          }
          this.form.spuSaleAttrList.push(obj)
        }
      } else {
        this.$message({ type: 'warning', message: '最多添加三个售卖属性' })
      }
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        if (!this.form.spuImageList) {
          this.form.spuImageList = []
        }
        this.form.spuImageList.push({
          id: undefined,
          imgName: file.name,
          imgUrl: res.data,
          spuId: this.form.id
        })
      } else {
        this.$message({ type: 'error', message: res.data || res.message })
      }
    },
    // 删除图片
    delSpuImg(obj) {
      this.form.spuImageList.splice(this.form.spuImageList.indexOf(obj), 1)
    },
    async saveInfo() {
      // 整理数据
      this.form.category3Id = this.category3Id
      // 非数字,没有进行选择
      if (isNaN(this.selectTradeMark * 1)) {
        // 编辑模式
        if (this.form.tmId) {
        }
        // 添加模式
        else {
          this.form.tmId = ''
        }
      } else {
        this.form.tmId = this.selectTradeMark
      }

      const res = await this.$API.spu.saveSpuInfo(this.form)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: this.form.id ? '修改成功' : '添加成功'
        })
        // 清空数据
        this.clearForm()
        // 回到index
        this.emitchangeShow(true)
      } else {
        this.$message({
          type: 'error',
          message:
            (this.form.id ? '修改失败' : '添加失败') + ':' + res.data || ''
        })
      }
    },
    cancel() {
      const { spuName, spuImageList, spuSaleAttrList, description } = this.form
      if (
        spuName ||
        spuImageList.length != 0 ||
        spuSaleAttrList.length != 0 ||
        description
      ) {
        this.$confirm('当前数据未保存是否返回?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
          .then(() => {
            this.clearForm()
            this.emitchangeShow()
          })
          .catch(() => {})
      } else {
        this.emitchangeShow()
      }
    },
    emitchangeShow(is_update, flag) {
      this.$emit('changeShow', is_update, flag)
    },
    clearForm() {
      this.selectTradeMark = '请选择品牌'
      this.form = {
        // 记得带上ID
        category3Id: this.category3Id,
        description: '',
        // 添加时无spuid
        id: undefined,
        // 品牌ID
        tmId: '',
        spuName: '',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: '',
          //   imgUrl: '',
          //   spuId: undefined
          // }
        ],
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: '',
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: '',
          //       saleAttrName: '',
          //       saleAttrValueName: '',
          //       spuId: undefined
          //     }
          //   ]
          // }
        ]
      }
    }
  },
  created() {
    this.$Bus.$on('editSpuInfo', this.getSpuInfoToEdit)
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 图片遮罩层 */
.showImgMaskLayer {
  --displayVal: none;
}
.showImgMaskLayer:hover {
  --displayVal: block;
}
.imgMaskLayer {
  display: var(--displayVal);
  text-align: center;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
}
</style>
